<template>
  <view class="container">
    <!-- 页面头部 -->
    <view class="header">
      <text class="title">趣味API</text>
    </view>

    <!-- API卡片网格 -->
    <view class="card-grid">
      <view
        v-for="(item, index) in apiList"
        :key="index"
        class="card"
        @click="handleApiClick(item)"
      >
        <view
          class="card-inner"
          :style="{
            background: item.bgColor,
            color: '#ffffff',
          }"
        >
          <view class="card-icon">
            <FeatherIcon :name="item.icon" :size="28" color="#ffffff" />
          </view>
          <view class="card-info">
            <text class="card-title" style="color: #ffffff">{{
              item.name
            }}</text>
            <text class="card-desc" style="color: rgba(255, 255, 255, 0.9)">{{
              item.desc
            }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 页面底部提示 -->
    <view class="footer">
      <text class="disclaimer"
        >声明：本页面提供的所有内容均来自第三方公开API接口，仅供娱乐和学习交流使用，不代表摸鱼派观点和立场，不保证内容的准确性、安全性和合法性，使用者需自行承担风险。</text
      >
    </view>

    <!-- 弹框遮罩层 -->
    <view class="modal-overlay" v-if="modalVisible" @click="closeModal"></view>

    <!-- 弹窗遮罩 -->
    <view class="modal-mask" v-if="modalVisible" @click="closeModal"></view>

    <!-- 内容弹窗 -->
    <view class="modal" v-if="modalVisible">
      <!-- 弹窗头部 -->
      <view class="modal-header">
        <text class="modal-title">{{ currentApi ? currentApi.name : "" }}</text>
        <view class="close-btn" @click="closeModal">
          <FeatherIcon name="x" size="24" color="#333" />
        </view>
      </view>

      <!-- 弹窗内容 -->
      <view class="modal-content">
        <!-- 加载中 -->
        <view class="loading-wrapper" v-if="isLoading">
          <view class="loading-spinner"></view>
          <text class="loading-text">{{ loadingText }}</text>
        </view>

        <!-- 视频内容 -->
        <template
          v-else-if="currentApi && currentApi.id === 'video' && videoUrl"
        >
          <video
            :src="videoUrl"
            class="content-video"
            controls
            autoplay
            :poster="videoPoster"
          ></video>
        </template>

        <!-- 图片内容 -->
        <template
          v-else-if="
            currentApi &&
            ((currentApi.id === 'hs_img' && imageUrl) ||
              (currentApi.id === 'moyu' && imageUrl))
          "
        >
          <view class="image-container">
            <view class="image-loading-wrapper" v-if="imageLoading">
              <view class="loading-spinner"></view>
              <text class="loading-text">{{ loadingText }}</text>
            </view>
            <image
              :src="imageUrl"
              class="content-image"
              mode="widthFix"
              @error="handleImageError"
              @load="handleImageLoad"
            ></image>
          </view>
        </template>

        <!-- 文字内容 -->
        <template
          v-else-if="currentApi && currentApi.id === 'dog' && dogContent"
        >
          <view class="content-text">
            <text>{{ dogContent }}</text>
          </view>
        </template>

        <!-- 加载失败 -->
        <view class="error-wrapper" v-else>
          <FeatherIcon name="alert-circle" size="56" color="#ff6b6b" />
          <text class="error-text">内容加载失败，请重试</text>
        </view>
      </view>

      <!-- 弹窗底部 -->
      <view class="modal-footer">
        <!-- 视频按钮 -->
        <template v-if="currentApi && currentApi.id === 'video'">
          <button class="btn save-btn" @click="saveVideo">
            <FeatherIcon name="download" size="18" color="#fff" />
            <text>保存</text>
          </button>
          <button class="btn refresh-btn" @click="loadContent">
            <FeatherIcon name="refresh-cw" size="18" color="#fff" />
            <text>换一个</text>
          </button>
        </template>

        <!-- 图片按钮 -->
        <template v-else-if="currentApi && currentApi.id === 'hs_img'">
          <button class="btn save-btn" @click="saveImage">
            <FeatherIcon name="download" size="18" color="#fff" />
            <text>保存</text>
          </button>
          <button class="btn refresh-btn" @click="loadContent">
            <FeatherIcon name="refresh-cw" size="18" color="#fff" />
            <text>换一个</text>
          </button>
        </template>

        <!-- 摸鱼日报按钮 -->
        <template v-else-if="currentApi && currentApi.id === 'moyu'">
          <button class="btn save-btn" @click="saveImage">
            <FeatherIcon name="download" size="18" color="#fff" />
            <text>保存</text>
          </button>
        </template>

        <!-- 文字按钮 -->
        <template v-else-if="currentApi && currentApi.id === 'dog'">
          <button class="btn copy-btn" @click="copyText">
            <FeatherIcon name="copy" size="18" color="#fff" />
            <text>复制</text>
          </button>
          <button class="btn refresh-btn" @click="loadContent">
            <FeatherIcon name="refresh-cw" size="18" color="#fff" />
            <text>换一个</text>
          </button>
        </template>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import FeatherIcon from "@/components/FeatherIcon.vue";
import { showLoading, hideLoading, showError } from "@/utils/common.js";

// API列表
const apiList = reactive([
  {
    id: "video",
    name: "小姐姐短视频",
    desc: "随机输出一条快手小姐姐短视频",
    icon: "film",
    color: "#fff",
    bgColor: "#ff6b81",
    url: "https://api.dwo.cc/api/ksvideo",
  },
  {
    id: "hs_img",
    name: "黑丝",
    desc: "随机精美黑丝图",
    icon: "image",
    color: "#fff",
    bgColor: "#5352ed",
    url: "https://api.dwo.cc/api/hs_img",
  },
  {
    id: "dog",
    name: "舔狗日记",
    desc: "做一个合格的舔狗",
    icon: "book",
    color: "#fff",
    bgColor: "#ff9800",
    url: "https://api.dwo.cc/api/dog",
  },
  {
    id: "moyu",
    name: "摸鱼日报",
    desc: "今日摸鱼周报",
    icon: "calendar",
    color: "#fff",
    bgColor: "#2ed573",
    url: "https://api.dwo.cc/api/moyu",
  },
]);

// 弹框相关
const modalVisible = ref(false);
const currentApi = ref(null);
const isLoading = ref(false);

// 资源URL
const videoUrl = ref("");
const imageUrl = ref("");
const dogContent = ref("");
const videoPoster = ref("/static/video-poster.png");

// 图片加载相关
const imageLoading = ref(false);

// 加载动画相关
const loadingText = ref("加载中");
let loadingInterval = null;

// 启动加载文本动画
const startLoadingAnimation = () => {
  let dots = 0;
  loadingInterval = setInterval(() => {
    dots = (dots + 1) % 4;
    loadingText.value = "加载中" + ".".repeat(dots);
  }, 500);
};

// 停止加载文本动画
const stopLoadingAnimation = () => {
  if (loadingInterval) {
    clearInterval(loadingInterval);
    loadingInterval = null;
  }
};

// 处理API点击
const handleApiClick = (item) => {
  currentApi.value = item;
  modalVisible.value = true;
  resetContent();
  loadContent();
  startLoadingAnimation();
};

// 关闭弹框
const closeModal = () => {
  modalVisible.value = false;
  stopLoadingAnimation();
  // 延迟一段时间后重置内容，避免关闭动画时看到内容重置
  setTimeout(() => {
    resetContent();
  }, 300);
};

// 重置内容
const resetContent = () => {
  videoUrl.value = "";
  imageUrl.value = "";
  dogContent.value = "";
  imageLoading.value = false;
};

// 加载内容
const loadContent = async () => {
  if (!currentApi.value || isLoading.value) return;

  isLoading.value = true;

  try {
    // 根据当前API类型加载不同内容
    switch (currentApi.value.id) {
      case "video":
        await loadVideo();
        break;
      case "hs_img":
        imageLoading.value = true;
        await loadImage();
        break;
      case "dog":
        await loadDogDiary();
        break;
      case "moyu":
        imageLoading.value = true;
        await loadMoyu();
        break;
    }
  } catch (error) {
    console.error("加载内容失败", error);
    showError("加载失败，请重试");
    imageLoading.value = false;
  } finally {
    isLoading.value = false;
  }
};

// 加载视频
const loadVideo = async () => {
  try {
    // 使用时间戳防止缓存
    const timestamp = new Date().getTime();

    // 直接使用downloadFile而不是request
    const downloadRes = await new Promise((resolve, reject) => {
      uni.downloadFile({
        url: `https://api.dwo.cc/api/ksvideo?t=${timestamp}`,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res);
          } else {
            reject(new Error("下载视频失败"));
          }
        },
        fail: (err) => {
          reject(err);
        },
      });
    });

    // 设置临时路径作为视频源
    videoUrl.value = downloadRes.tempFilePath;
  } catch (error) {
    console.error("加载视频失败", error);
    throw error;
  }
};

// 加载图片
const loadImage = async () => {
  try {
    // 使用时间戳防止缓存
    const timestamp = new Date().getTime();
    const res = await uni.request({
      url: `https://api.dwo.cc/api/hs_img?t=${timestamp}`,
      method: "GET",
    });

    if (res.statusCode === 200) {
      // 处理返回的JSON格式数据
      if (
        typeof res.data === "object" &&
        res.data.状态 === "成功" &&
        res.data.数据
      ) {
        imageUrl.value = res.data.数据.pic;
      } else {
        // 兼容旧格式
        imageUrl.value = res.data;
      }
    } else {
      throw new Error("获取图片失败");
    }
  } catch (error) {
    console.error("加载图片失败", error);
    throw error;
  }
};

// 加载舔狗日记
const loadDogDiary = async () => {
  try {
    // 使用时间戳防止缓存
    const timestamp = new Date().getTime();
    const res = await uni.request({
      url: `https://api.dwo.cc/api/dog?t=${timestamp}`,
      method: "GET",
    });

    if (res.statusCode === 200) {
      // 处理返回的JSON格式数据
      if (typeof res.data === "object" && res.data.code === 200) {
        dogContent.value = res.data.text;
      } else {
        dogContent.value = res.data;
      }
    } else {
      throw new Error("获取舔狗日记失败");
    }
  } catch (error) {
    console.error("加载舔狗日记失败", error);
    throw error;
  }
};

// 加载摸鱼日报
const loadMoyu = async () => {
  try {
    // 使用时间戳防止缓存
    const timestamp = new Date().getTime();

    // 直接使用downloadFile而不是request
    const downloadRes = await new Promise((resolve, reject) => {
      uni.downloadFile({
        url: `https://api.dwo.cc/api/moyu?t=${timestamp}`,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res);
          } else {
            reject(new Error("下载摸鱼日报失败"));
          }
        },
        fail: (err) => {
          reject(err);
        },
      });
    });

    // 设置临时路径作为图片源
    imageUrl.value = downloadRes.tempFilePath;
  } catch (error) {
    console.error("加载摸鱼日报失败", error);
    throw error;
  }
};

// 保存图片
const saveImage = () => {
  if (!imageUrl.value) return;

  uni.showLoading({ title: "保存中..." });

  uni.downloadFile({
    url: imageUrl.value,
    success: (res) => {
      if (res.statusCode === 200) {
        uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            uni.showToast({
              title: "保存成功",
              icon: "success",
            });
          },
          fail: (err) => {
            console.error("保存图片失败", err);
            showError("保存失败，请检查权限设置");
          },
        });
      } else {
        showError("下载图片失败");
      }
    },
    fail: () => {
      showError("下载图片失败");
    },
    complete: () => {
      uni.hideLoading();
    },
  });
};

// 保存视频
const saveVideo = () => {
  if (!videoUrl.value) return;

  uni.showLoading({ title: "保存中..." });

  // 视频已经在本地，直接保存
  uni.saveVideoToPhotosAlbum({
    filePath: videoUrl.value,
    success: () => {
      uni.showToast({
        title: "保存成功",
        icon: "success",
      });
    },
    fail: (err) => {
      console.error("保存视频失败", err);
      showError("保存失败，请检查权限设置");
    },
    complete: () => {
      uni.hideLoading();
    },
  });
};

// 复制文字
const copyText = () => {
  if (!dogContent.value) return;

  uni.setClipboardData({
    data: dogContent.value,
    success: () => {
      uni.showToast({
        title: "复制成功",
        icon: "success",
      });
    },
  });
};

// 处理图片加载错误
const handleImageError = () => {
  showError("图片加载失败，请点击刷新按钮重试");
};

// 处理图片加载完成
const handleImageLoad = () => {
  imageLoading.value = false;
};

// 组件卸载时清理定时器
onUnmounted(() => {
  stopLoadingAnimation();
});

// 页面加载
onMounted(() => {
  // 初始化
});
</script>

<style lang="scss">
/* 主容器 */
.container {
  background-color: #f9f9f9;
  padding: 24rpx;
}

/* 头部样式 */
.header {
  margin-top: 48rpx;
  margin-bottom: 28rpx;

  .title {
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
    position: relative;
    display: inline-block;

    &::after {
      content: "";
      position: absolute;
      bottom: -8rpx;
      left: 0;
      width: 60rpx;
      height: 6rpx;
      background: #3f51b5;
      border-radius: 3rpx;
    }
  }
}

/* 卡片网格 */
.card-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx;
}

/* 卡片样式 */
.card {
  width: 50%;
  padding: 10rpx;
  box-sizing: border-box;
  margin-bottom: 8rpx;

  .card-inner {
    border-radius: 16rpx;
    overflow: hidden;
    padding: 24rpx;
    height: 140rpx;
    display: flex;
    align-items: center;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
    transition: transform 0.2s, box-shadow 0.2s;

    &:active {
      transform: scale(0.96);
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    }
  }

  .card-icon {
    width: 56rpx;
    height: 56rpx;
    margin-right: 16rpx;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
  }

  .card-info {
    flex: 1;
    overflow: hidden;
  }

  .card-title {
    font-size: 28rpx;
    font-weight: 600;
    color: white;
    margin-bottom: 6rpx;
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .card-desc {
    font-size: 22rpx;
    color: rgba(255, 255, 255, 0.9);
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

/* 页脚样式 */
.footer {
  margin-top: 40rpx;
  padding: 20rpx;
  text-align: center;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 10;

  .disclaimer {
    font-size: 24rpx;
    color: #888;
    line-height: 1.6;
    padding: 0 20rpx;
  }
}

/* 弹窗样式 */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  z-index: 100;
  backdrop-filter: blur(4px);
  animation: fadeIn 0.2s;
}

.modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 90%;
  max-width: 640rpx;
  background: white;
  border-radius: 20rpx;
  z-index: 101;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
  animation: scaleIn 0.3s;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 24rpx 30rpx;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .modal-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
  }

  .close-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;

    &:active {
      background: rgba(0, 0, 0, 0.05);
    }
  }
}

.modal-content {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;

  .content-video {
    width: 100%;
    height: 360rpx;
    border-radius: 12rpx;
    background: #000;
  }

  .content-image {
    width: 100%;
    border-radius: 12rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  }

  .image-container {
    position: relative;
    width: 100%;
    min-height: 300rpx;
  }

  .image-loading-wrapper {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: #f5f5f5;
    border-radius: 12rpx;
    min-height: 300rpx;

    .loading-spinner {
      width: 70rpx;
      height: 70rpx;
      border: 4rpx solid #f3f3f3;
      border-top: 4rpx solid #3f51b5;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 16rpx;
    }

    .loading-text {
      font-size: 26rpx;
      color: #666;
      position: relative;
      animation: dotAnimation 1.5s infinite;
    }
  }

  .content-text {
    background: #f8f8f8;
    border-radius: 12rpx;
    padding: 30rpx;
    font-size: 28rpx;
    line-height: 1.6;
    color: #333;
    border-left: 4rpx solid #3f51b5;
  }
}

.loading-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;

  .loading-spinner {
    width: 70rpx;
    height: 70rpx;
    border: 4rpx solid #f3f3f3;
    border-top: 4rpx solid #3f51b5;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 16rpx;
  }

  .loading-text {
    font-size: 26rpx;
    color: #666;
    position: relative;
    animation: dotAnimation 1.5s infinite;
  }
}

.error-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;

  .error-text {
    margin-top: 16rpx;
    font-size: 26rpx;
    color: #666;
  }
}

.modal-footer {
  padding: 20rpx 30rpx 30rpx;
  display: flex;
  justify-content: center;
  gap: 16rpx;

  .btn {
    min-width: 180rpx;
    height: 76rpx;
    border-radius: 38rpx;
    font-size: 26rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
    border: none;

    text {
      margin-left: 8rpx;
    }
  }

  .refresh-btn {
    background: #3f51b5;
    color: white;
  }

  .save-btn {
    background: #4caf50;
    color: white;
  }

  .copy-btn {
    background: #ff9800;
    color: white;
  }
}

/* 动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes scaleIn {
  from {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes dotAnimation {
  0% {
    content: "图片加载中";
  }
  25% {
    content: "图片加载中.";
  }
  50% {
    content: "图片加载中..";
  }
  75% {
    content: "图片加载中...";
  }
  100% {
    content: "图片加载中";
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}
</style>
